package mysql

import (
	"database/sql"
	"fmt"

	"woanju/models"
)

// CheGuardianExist  检查指定用户的监护人是否存在
func CheckGuardianExist(user_id int64) (err error) {
	sqlStr := `select count(guardian_id) from guardian where user_id = ?`

	var count int
	if err = db.Get(&count, sqlStr, user_id); err != nil {
		return err
	}
	if count > 0 {
		return ErrorGuardianExist
	}
	return ErrorGuardianNotExist
}

func InsertGuardian(g *models.Guardian) error {
	sqlStr := `insert into guardian(guardian_id,user_id,guardian_name,phone,email) values(?,?,?,?,?)`
	_, err := db.Exec(sqlStr, g.GuardianID, g.UserID, g.GuardianName, g.Phone, g.Email)
	return err
}

func GetGuardianInfo(uid int64) (*models.Guardian, error) {
	sqlStr := `select guardian_id,guardian_name,phone,email from guardian where user_id = ?`
	g := new(models.Guardian)
	err := db.Get(g, sqlStr, uid)
	fmt.Println(g)
	if err == sql.ErrNoRows {
		return nil, ErrorGuardianNotExist
	}
	if err != nil {
		return nil, err
	}

	return g, nil
}

func UpdateGuardian(g *models.Guardian) error {
	fmt.Println("0000000000")
	new_g, err := GetGuardianInfo(g.UserID)
	if err != nil {
		return err
	}
	fmt.Println("111111111")
	err = DeleteGuardian(g.UserID)
	if err != nil {
		return err
	}
	fmt.Println("222222222")

	g.GuardianID = new_g.GuardianID
	return InsertGuardian(g)
}

func DeleteGuardian(uid int64) error {
	sqlStr := `delete from guardian where user_id = ?`
	_, err := db.Exec(sqlStr, uid)
	if err == sql.ErrNoRows {
		return ErrorGuardianExist
	}
	return err
}
